package com.timmy.ble;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.Code;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleReadRssiResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.UUIDUtils;
import com.timmy.ble.callback.BleCallback;
import com.timmy.ble.callback.BleCallbackImpl;

import java.util.UUID;

import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;

/**
 * 单例设计模式
 */
public class BleManager {

    private static final String TAG = BleManager.class.getSimpleName();
    private static volatile BleManager instance = null;
    private static BluetoothClient mClient;
    private String MAC = "";

    private BleManager() {

    }

    public static BleManager getInstance(Context context) {
        if (instance == null) {
            synchronized (BleManager.class) {
                if (instance == null) {
                    mClient = new BluetoothClient(context);
                    instance = new BleManager();
                }
            }
        }
        return instance;
    }

    // 判断蓝牙是否打开
    public boolean isBluetoothOpened() {
        return mClient.isBluetoothOpened();
    }

    // 打开或者关闭蓝牙
    public void openOrCloseBle() {
        if (isBluetoothOpened()) {
            // 蓝牙已打开
            mClient.closeBluetooth();
        } else {
            // 蓝牙已关闭
            mClient.openBluetooth();
        }
    }

    // 注册蓝牙打开关闭时间的监听
    public void registerBluetoothStateListener(BluetoothStateListener l) {
        mClient.registerBluetoothStateListener(l);
    }

    public void unregisterBluetoothStateListener(BluetoothStateListener l) {
        mClient.unregisterBluetoothStateListener(l);
    }


    // 扫描蓝牙
    public void search(final BleCallback callback) {
        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
                .build();

        mClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                Log.i(TAG, "开始扫描");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                String name = device.getName();
                if (!TextUtils.isEmpty(name)) {
                    callback.onScan(device);
                }
            }

            @Override
            public void onSearchStopped() {
                callback.onScanStop();
            }

            @Override
            public void onSearchCanceled() {
                callback.onScanStop();
            }
        });
    }

    // 停止扫描
    public void stopSearch() {
        mClient.stopSearch();
    }

    // 获取设备的信号强度
    public void getDeviceSsi(String mac, final BleCallbackImpl callback) {
        mClient.readRssi(MAC, new BleReadRssiResponse() {
            @Override
            public void onResponse(int code, Integer data) {
                callback.onResponse(code, data);
            }
        });

    }

    // 蓝牙连接
    public void connect(String MAC, final BleConnectResponse response) {
        this.MAC = MAC;
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(3)   // 连接如果失败重试3次
                .setConnectTimeout(30000)   // 连接超时30s
                .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                .setServiceDiscoverTimeout(20000)  // 发现服务超时20s
                .build();

        mClient.connect(MAC, options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {

                if (code == Code.REQUEST_SUCCESS) {
                    Log.i(TAG, "连接成功");

                } else if (code == Code.REQUEST_FAILED) {
                    Log.i(TAG, "连接失败");

                }
                response.onResponse(code, data);
            }
        });
    }

    // 断开连接
    public void disconnect() {
        if (!TextUtils.isEmpty(MAC)) {
            mClient.disconnect(MAC);
        }
    }

    // 写入数据
    public void write(byte[] bytes, final BleWriteResponse response) {
        mClient.write(MAC, getUUID(0001), getUUID(0002), bytes, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                response.onResponse(code);
            }
        });
    }

    // 开启通知
    public void openNotify(final BleNotifyResponse response) {
        mClient.notify(MAC, getUUID(0001), getUUID(0003), new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                response.onNotify(service, character, value);
            }

            @Override
            public void onResponse(int code) {
                response.onResponse(code);
                if (code == Code.REQUEST_SUCCESS) {
                }
            }
        });
    }

    // 蓝牙连接状态监听
    public void registerConnectStatusListener(BleConnectStatusListener listener) {
        mClient.registerConnectStatusListener(MAC, mBleConnectStatusListener);
    }

    private final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {

        @Override
        public void onConnectStatusChanged(String mac, int status) {
            if (status == STATUS_CONNECTED) {
                Log.i(TAG, "蓝牙已连接");
            } else if (status == STATUS_DISCONNECTED) {
                Log.i(TAG, "蓝牙断开");

                // 断开执行重新连接功能

                if (true) {
                    return;
                }

                /**
                connect(MAC, new BleConnectResponse() {
                    @Override
                    public void onResponse(int code, BleGattProfile data) {

                        if (code == Code.REQUEST_SUCCESS) {
                            Log.i(TAG, "连接成功");

                        } else if (code == Code.REQUEST_FAILED) {
                            Log.i(TAG, "连接失败");

                        }
                    }
                });
                 */
            }
        }
    };

    public void unregisterConnectStatusListener() {
        mClient.unregisterConnectStatusListener(MAC, mBleConnectStatusListener);
    }


    private UUID getUUID(int uuid) {
        return UUIDUtils.makeUUID(uuid);
    }


    // 判断是否是主线程
    public static boolean isInMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public String getMac() {
        return MAC;
    }


}
